<?php
namespace app\erp_meixingtiyu\logic;

use app\erp_meixingtiyu\model\Booking as BookingModel;
class Booking
{
    public function addBooking($params, $user_id)
    {
        $start_date = $params['betweenTime'][0];
        $end_date = $params['betweenTime'][1];
        // 创建一个唯一的操作号代替订单号
        $order_no = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        // 创建一个预订操作记录
        $booking = new BookingModel();
        $booking->save(
            array_merge($params, compact('user_id', 'start_date', 'end_date', 'order_no'))
        );
        $list = [];
        foreach ($params['fragments'] as $key => $fragment_id) {
            $time_fragment = $params['fragments_str'][$key];
            $part_time_fragment_id = $params['part_time_fragment_ids'][$key];
            $list[] = array_merge(
                $params,
                compact(
                    'user_id',
                    'start_date',
                    'end_date',
                    'fragment_id',
                    'time_fragment',
                    'part_time_fragment_id'
                )
            );
        }
        $result = $booking->fragments()->saveAll($list);
        return $result;
    }

    // 根据日期范围获取预订记录
  public function getListByDate($dateArr)
  {
    [$startDate, $endDate] = $dateArr;
    $endDateArr = explode('-', $endDate);
    $endDateArr[2] = (int)$endDateArr[2] + 1;
    $endDate = implode('-', $endDateArr);
    $list = (new BookingModel)->selectListByDate($startDate, $endDate);
    return $list->toArray();
  }
}
